package com.security.antitheft.ui;

import android.app.Activity;

import android.app.Dialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.security.antitheft.R;
import com.security.antitheft.module.ShareSetting;
import com.security.antitheft.service.BootService;
import com.security.antitheft.service.DeviceAdminPmsReceiver;

public class AntiTheftSettingActivity extends Activity implements android.view.View.OnClickListener {

	private Button btnSave;
	private EditText editPin;
	private TextView txtImei;
	private ImageButton btnOn[] = new ImageButton[]{null, null, null, null};
	private ImageButton btnOff[] = new ImageButton[] {null, null, null, null};

	private boolean enableLocation, enableLock, enableErase, enablePins;

	private final int ENTER_PIN_DIALOG = 1;
	private final static int RANDOM_PASSWORD_DIGIT = 8;
	private final static int LOCK_FROM_REMOTE_MSG = 100;
	private final static int VISIBLE_FROM_REMOTE_MSG = 104;
	
	private final static int REQUEST_CODE_ENABLE_ADMIN = 1;
	private final static String LOCK_KEY_FROM_REMOTE = "111q";
	
	//k-review
	Context mContext = null;
	private LockStateThread mLockThread = null;
	DevicePolicyManager mDPM = null;
	ComponentName mAdminComp;
	String mRandomPwd = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		//k-review
		mLockThread = new LockStateThread(true);
		mLockThread.start();
		mContext = this;
		mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
		mAdminComp = new ComponentName(this, DeviceAdminPmsReceiver.class);
		
		mRandomPwd = ShareUISetting.GetRandomPassword(this);
		if(mRandomPwd == null || mRandomPwd.length() == 0)
		{
			mRandomPwd = randomPassword(RANDOM_PASSWORD_DIGIT);
			ShareUISetting.SetRandomPassword(this, mRandomPwd);
		}
		
		//check admin permission
		//activateDeviceAdmin();
		
		startService(new Intent(this, BootService.class));
	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.i("AntiTheftSettingActivity", "=======AntiTheftSettingActivity===onResume");
		activateDeviceAdmin();		
		super.onResume();
		if (ShareUISetting.isEnablePins(this)) {
			showDialog(ENTER_PIN_DIALOG);
		} else {
			populateForm();
		}
	}
	
	//k-review
	@Override
	protected void onPause() {
		Log.i("AntiTheftSettingActivity", "=======AntiTheftSettingActivity===onPause");
		super.onPause();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		Log.i("AntiTheftSettingActivity", "=====AntiTheftSettingActivity=====onStop");
		deActivateDeviceAdmin();
	}
	
	//k-review
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i("AntiTheftSettingActivity", "=====AntiTheftSettingActivity=====onDestroy");
		mLockThread.stopThread();
		deActivateDeviceAdmin();
	}
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btnOnLoc:
			enableLocation = true;
			btnOn[0].setImageDrawable(getResources().getDrawable(enableLocation?R.drawable.on_1:R.drawable.on_2));
			btnOff[0].setImageDrawable(getResources().getDrawable(!enableLocation?R.drawable.off_1:R.drawable.off_2));
			break;
		case R.id.btnOffLoc:
			enableLocation = false;
			btnOn[0].setImageDrawable(getResources().getDrawable(enableLocation?R.drawable.on_1:R.drawable.on_2));
			btnOff[0].setImageDrawable(getResources().getDrawable(!enableLocation?R.drawable.off_1:R.drawable.off_2));
			break;
		case R.id.btnOnLock:
			enableLock = true;
			btnOn[1].setImageDrawable(getResources().getDrawable(enableLock?R.drawable.on_1:R.drawable.on_2));
			btnOff[1].setImageDrawable(getResources().getDrawable(!enableLock?R.drawable.off_1:R.drawable.off_2));
			break;
		case R.id.btnOffLock:
			enableLock = false;
			btnOn[1].setImageDrawable(getResources().getDrawable(enableLock?R.drawable.on_1:R.drawable.on_2));
			btnOff[1].setImageDrawable(getResources().getDrawable(!enableLock?R.drawable.off_1:R.drawable.off_2));
			break;
		case R.id.btnOnEra:
			enableErase = true;
			btnOn[2].setImageDrawable(getResources().getDrawable(enableErase?R.drawable.on_1:R.drawable.on_2));
			btnOff[2].setImageDrawable(getResources().getDrawable(!enableErase?R.drawable.off_1:R.drawable.off_2));
			break;
		case R.id.btnOffEra:
			enableErase = false;
			btnOn[2].setImageDrawable(getResources().getDrawable(enableErase?R.drawable.on_1:R.drawable.on_2));
			btnOff[2].setImageDrawable(getResources().getDrawable(!enableErase?R.drawable.off_1:R.drawable.off_2));
			break;
		case R.id.btnOnPin:
			enablePins = true;
			btnOn[3].setImageDrawable(getResources().getDrawable(enablePins?R.drawable.on_1:R.drawable.on_2));
			btnOff[3].setImageDrawable(getResources().getDrawable(!enablePins?R.drawable.off_1:R.drawable.off_2));
			editPin.setEnabled(enablePins);
			break;
		case R.id.btnOffPin:
			enablePins = false;
			btnOn[3].setImageDrawable(getResources().getDrawable(enablePins?R.drawable.on_1:R.drawable.on_2));
			btnOff[3].setImageDrawable(getResources().getDrawable(!enablePins?R.drawable.off_1:R.drawable.off_2));
			editPin.setEnabled(enablePins);
			break;
		case R.id.btnSave:
			String pin = editPin.getText().toString();
			if (enablePins && pin.equals("")) {
				Toast.makeText(this, "Please input PIN code.", Toast.LENGTH_LONG).show();
				return;
			}
			ShareUISetting.saveSettings(this, enableLocation, enableLock, enableErase, enablePins, pin);
			ShareUISetting.setAppFlag(this, ShareUISetting.OPT_CHANGED);
			Toast.makeText(this, "Save Success", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final Dialog dialog;
		switch(id) {
		case ENTER_PIN_DIALOG:
			dialog = new Dialog(this, R.style.Theme_Dialog);
			dialog.setContentView(R.layout.enter_pin);
			Window window = dialog.getWindow();
			window.setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			window.setGravity(Gravity.CENTER);
 
			// set the custom dialog components - text, image and button
			final EditText text = (EditText) dialog.findViewById(R.id.editPin);
			Button okButton = (Button) dialog.findViewById(R.id.btnSave);
			okButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					String pin = text.getText().toString();
					if (pin.equals(ShareUISetting.pins(AntiTheftSettingActivity.this))) {
						dialog.dismiss();
						text.setText("");
						populateForm();
					} else {
						text.setText("");
						text.requestFocus();
					}
				}
			});
			Button cancelButton = (Button) dialog.findViewById(R.id.btnCancel);
			cancelButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					finish();
				}
			});
			
			//k-review
			dialog.setCancelable(false);
			dialog.setOnDismissListener(new OnDismissListener() {
	            @Override
	            public void onDismiss(DialogInterface dialog) {
	            	if(ShareUISetting.isEnablePins(mContext) && ShareSetting.GetLockFromRemote(mContext))
	            	{
	            		Log.e("AntiTheft", "========== dialog back pressed");
	            		return;
	            	}
	            }
	        });
			
			break;
		default:
			dialog = null;

		}
		return dialog;
	}
	
	private void visibleRemoteOptions()
	{
		//k-review
		RelativeLayout rlVisibleLocation = (RelativeLayout) findViewById(R.id.relativeLayout2);
		RelativeLayout rlVisibleLock = (RelativeLayout) findViewById(R.id.relativeLayout3);
		RelativeLayout rlVisibleErase = (RelativeLayout) findViewById(R.id.relativeLayout4);
		RelativeLayout rlVisiblePins = (RelativeLayout) findViewById(R.id.relativeLayoutPins);
		
		//BG_17.06.2013: Check in case if contentView is not initialized,
		// this is the case when the PIN dialog is being shown.
		
		if(rlVisibleLocation != null)
			if(ShareUISetting.GetVSRemoteLocation(this))
				rlVisibleLocation.setVisibility(View.VISIBLE);
			else
				rlVisibleLocation.setVisibility(View.GONE);

		if(rlVisibleLock != null)
			if(ShareUISetting.GetVSRemoteLock(this))
				rlVisibleLock.setVisibility(View.VISIBLE);
			else
				rlVisibleLock.setVisibility(View.GONE);

		if(rlVisibleErase != null)
			if(ShareUISetting.GetVSRemoteErase(this))
				rlVisibleErase.setVisibility(View.VISIBLE);
			else
				rlVisibleErase.setVisibility(View.GONE);

		if(rlVisiblePins != null)
			if(ShareUISetting.GetVSRemotePins(this))
				rlVisiblePins.setVisibility(View.VISIBLE);
			else
				rlVisiblePins.setVisibility(View.GONE);
	}
	
	private void populateForm() {
		setContentView(R.layout.home);
		btnSave = (Button) findViewById(R.id.btnSave);
		editPin = (EditText) findViewById(R.id.editPin);
		txtImei = (TextView) findViewById(R.id.txtImei);
		btnOn[0] = (ImageButton) findViewById(R.id.btnOnLoc);
		btnOn[1] = (ImageButton) findViewById(R.id.btnOnLock);
		btnOn[2] = (ImageButton) findViewById(R.id.btnOnEra);
		btnOn[3] = (ImageButton) findViewById(R.id.btnOnPin);
		btnOff[0] = (ImageButton) findViewById(R.id.btnOffLoc);
		btnOff[1] = (ImageButton) findViewById(R.id.btnOffLock);
		btnOff[2] = (ImageButton) findViewById(R.id.btnOffEra);
		btnOff[3] = (ImageButton) findViewById(R.id.btnOffPin);
		for (int i = 0; i < 4; i++) {
			btnOff[i].setOnClickListener(this);
			btnOn[i].setOnClickListener(this);
		}
		btnSave.setOnClickListener(this);
		
		enableLocation = ShareUISetting.isEnableRemoteLocation(this);
		enableLock = ShareUISetting.isEnableRemoteLock(this);
		enableErase = ShareUISetting.isEnableRemoteErase(this);
		enablePins = ShareUISetting.isEnablePins(this);
		
		btnOn[0].setImageDrawable(getResources().getDrawable(enableLocation?R.drawable.on_1:R.drawable.on_2));
		btnOff[0].setImageDrawable(getResources().getDrawable(!enableLocation?R.drawable.off_1:R.drawable.off_2));
		btnOn[1].setImageDrawable(getResources().getDrawable(enableLock?R.drawable.on_1:R.drawable.on_2));
		btnOff[1].setImageDrawable(getResources().getDrawable(!enableLock?R.drawable.off_1:R.drawable.off_2));
		btnOn[2].setImageDrawable(getResources().getDrawable(enableErase?R.drawable.on_1:R.drawable.on_2));
		btnOff[2].setImageDrawable(getResources().getDrawable(!enableErase?R.drawable.off_1:R.drawable.off_2));
		btnOn[3].setImageDrawable(getResources().getDrawable(enablePins?R.drawable.on_1:R.drawable.on_2));
		btnOff[3].setImageDrawable(getResources().getDrawable(!enablePins?R.drawable.off_1:R.drawable.off_2));
		editPin.setEnabled(enablePins);
		
		TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
		txtImei.setText(mngr.getDeviceId());
		if (enablePins) {
			editPin.setText(ShareUISetting.pins(this));
		}
		
		//k-review
		visibleRemoteOptions();
		
		//random password
		TextView tvPassword = (TextView)findViewById(R.id.txtPassword);
		tvPassword.setText(mRandomPwd);
	}
	
	//random password
	public static String randomPassword(int nLen)
	{
		int index = 0;
		char[] szChrArr = new char[]{
				'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
				'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
				'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
				'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
				};
		
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<nLen; i++)
		{
			index = (int)(szChrArr.length * Math.random());
			sb.append(szChrArr[index]);
		}
		
		return sb.toString();		
	}
	
	private void activateDeviceAdmin()
	{
		boolean bLockRelease = ShareSetting.GetLockRelease(this);
		if(bLockRelease)
			return;
		
		//check admin permission
//		if(mDPM.isAdminActive(mAdminComp))
//		{
//			//Toast.makeText(mContext, "Already,, You get admin permission", Toast.LENGTH_SHORT).show();
//		}
//		else
//		{
//            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminComp);
//            //intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "add_admin_extra_app_text");
//            startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
//		}		
	}
	
	private void deActivateDeviceAdmin()
	{
		//deactivate admin permission
//		if(mDPM.isAdminActive(mAdminComp))
//		{
//			Toast.makeText(this, "Admin Permission is release", Toast.LENGTH_SHORT).show();
//			mDPM.removeActiveAdmin(mAdminComp);
//		}
//		else
//		{
//			//Toast.makeText(this, "Already,,, admin permission is release", Toast.LENGTH_SHORT).show();
//		}		
	}
	
	Handler mLockHandler = new Handler() {
	    @Override
	    public void handleMessage(Message msg) 
	    {
	    	super.handleMessage(msg);
	    	
	    	if (msg.what == LOCK_FROM_REMOTE_MSG)
	    	{
	    		Log.e("AntiTheft", "========== setting Lock from Remote++++");
	    		
	    		if(mDPM.isAdminActive(mAdminComp))
	    		{
	    			ShareSetting.SetLockFromRemote(mContext, false);
	    			ShareSetting.SetLockRelease(mContext, true);
	    			mDPM.resetPassword(LOCK_KEY_FROM_REMOTE, DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY);
	    			mDPM.lockNow();
	    			finish();
	    		}
	    	}
	    	
	    	if(msg.what == VISIBLE_FROM_REMOTE_MSG)
	    		visibleRemoteOptions();
	    }
	};  
	
	private void LockFromRemote()
	{
		//Log.i("AntiTheft", "========== Checking LockState from Remote++++");
		
		boolean bLockFromRemote = ShareSetting.GetLockFromRemote(this);
		if(bLockFromRemote)
		{
			boolean bLockRelease = ShareSetting.GetLockRelease(this);
			if(bLockRelease)
			{
				Log.e("AntiTheft", "========== LockFromRemote --- release -- true");
				return;
			}
			
		    Message msg = new Message();
			  
		    msg.what = LOCK_FROM_REMOTE_MSG;
		    mLockHandler.sendMessage(msg);
		}
		else
		{
		    Message msg = new Message();
			  
		    msg.what = VISIBLE_FROM_REMOTE_MSG;
		    mLockHandler.sendMessage(msg);
		}
	}
	
	//k-review
	class LockStateThread extends Thread {
		private int i = 0;
		private boolean isLock = false;

		public LockStateThread(boolean isLock) {
			this.isLock = isLock;
		}

		public void stopThread() {
			isLock = false;
		}

		@Override
		public void run() {
			super.run();
			while (isLock) 
			{
				try {
					Thread.sleep(1000);
					LockFromRemote();					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}



